package com.cloud.utils;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.List;

public class ZooKeeperUtil {

    private static final int SESSION_TIMEOUT = 3000;
    private ZooKeeper zooKeeper;

    public ZooKeeperUtil(String connectString) throws IOException {
        this.zooKeeper = new ZooKeeper(connectString, SESSION_TIMEOUT, new DefaultWatcher());
    }

    public void createNode(String path, byte[] data) throws KeeperException, InterruptedException {

        zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    public byte[] getNodeData(String path) throws KeeperException, InterruptedException {

        return zooKeeper.getData(path, false, null);
    }

    public List<String> getChildren(String path) throws KeeperException, InterruptedException {

        return zooKeeper.getChildren(path, false);
    }

    public void close() throws InterruptedException {

        zooKeeper.close();
    }

    private static class DefaultWatcher implements Watcher {

        @Override
        public void process(WatchedEvent event) {

            // Handle events if needed
        }
    }
}